Research
Security News
Threat Actor Exposes Playbook for Exploiting npm to Build Blockchain-Powered Botnets
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
memoize-one
Advanced tools
The memoize-one package is a simple and lightweight memoization library designed for memoizing the result of a function based on the latest arguments. It only remembers the latest arguments and result, and it will only recompute the result when the arguments change. This can be particularly useful for optimizing performance in scenarios where expensive function calls are frequently made with the same arguments.
Simple memoization of functions
This feature allows you to create a memoized version of a function that caches the result based on the latest set of arguments it was called with. If the function is called again with the same arguments, the cached result is returned instead of recomputing.
const memoizeOne = require('memoize-one');
const add = (a, b) => a + b;
const memoizedAdd = memoizeOne(add);
console.log(memoizedAdd(1, 2)); // 3
console.log(memoizedAdd(1, 2)); // 3, cached result
console.log(memoizedAdd(2, 2)); // 4, recomputed because arguments changed
Custom equality function
This feature allows you to provide a custom function to compare the equality of arguments. This is useful when you need to memoize a function that takes complex arguments like objects or arrays and the default shallow comparison is not sufficient.
const memoizeOne = require('memoize-one');
const isEqual = (newArgs, lastArgs) => JSON.stringify(newArgs) === JSON.stringify(lastArgs);
const complexFunction = (obj) => {/* complex operation */};
const memoizedComplexFunction = memoizeOne(complexFunction, isEqual);
Lodash provides a memoize function that can cache the result of function calls based on the arguments passed. It allows for custom cache implementations and is part of the larger Lodash utility library, which provides a wide range of functions for manipulating and traversing data.
Fast-memoize is a high-performance memoization library that claims to be the fastest possible memoization library in JavaScript. It supports multiple argument memoization and provides various options for cache creation, argument serialization, and strategy selection.
Reselect is a selector library for Redux that uses memoization to efficiently compute derived data from the Redux store. It is specifically designed for use with Redux and allows for creating memoized selector functions that can compute derived data, optimizing performance for Redux applications.
A memoization library that only caches the result of the most recent arguments.
Cache invalidation is hard:
There are only two hard things in Computer Science: cache invalidation and naming things.
Phil Karlton
So keep things simple and just use a cache size of one!
Unlike other memoization libraries, memoize-one
only remembers the latest arguments and result. No need to worry about cache busting mechanisms such as maxAge
, maxSize
, exclusions
and so on which can be prone to memory leaks. memoize-one
simply remembers the last arguments, and if the function is next called with the same arguments then it returns the previous result.
import memoizeOne from 'memoize-one';
const add = (a, b) => a + b;
const memoizedAdd = memoizeOne(add);
memoizedAdd(1, 2); // 3
memoizedAdd(1, 2); // 3
// Add function is not executed: previous result is returned
memoizedAdd(2, 3); // 5
// Add function is called to get new value
memoizedAdd(2, 3); // 5
// Add function is not executed: previous result is returned
memoizedAdd(1, 2); // 3
// Add function is called to get new value.
// While this was previously cached,
// it is not the latest so the cached result is lost
You can also pass in a custom function for checking the equality of two items. The equality function will is used to compare the value of every individual argument.
import memoizeOne from 'memoize-one';
import deepEqual from 'lodash.isEqual';
const identity = x => x;
const defaultMemoization = memoizeOne(identity);
const customMemoization = memoizeOne(identity, deepEqual);
const result1 = defaultMemoization({foo: 'bar'});
const result2 = defaultMemoization({foo: 'bar'});
result1 === result2 // false - difference reference
const result3 = customMemoization({foo: 'bar'});
const result4 = customMemoization({foo: 'bar'});
result3 === result4 // true - arguments are deep equal
Here is the expected flow type signature for a custom equality function:
type EqualityFn = (newValue: mixed, oldValue: mixed, index: number) => boolean;
The default equality function is a simple shallow equal check
const simpleIsEqual: EqualityFn = (a: mixed, b: mixed): boolean => a === b;
If the function you want to memoize takes multiple arguments, your custom equality function will be called once for each argument and will be passed each argument's new value and last value.
import memoizeOne from 'memoize-one';
const makeCountObj = (first, second, third) => ({
first: first.count,
second: second.count,
third: third.count,
});
const areCountPropertiesEqual = (newArg, lastArg) => newArg.count === lastArg.count;
// runs once for first's new and last values, once for second's, etc.
const memoizedMakeCountObj = memoizeOne(makeCountObj, areCountPropertiesEqual);
const result1 = memoizedMakeCountObj(
{a: '?', count: 1},
{a: '$', count: 2},
{a: '#', count: 3}
);
const result2 = memoizedMakeCountObj(
{b: null, count: 1},
{b: null, count: 2},
{b: null, count: 3}
);
result1 === result2; // true - same reference
For each call of the equality function you are provided with the index of the argument.
import memoizeOne from 'memoize-one';
import deepEqual from 'lodash.isEqual';
const myEqualFn = (newArg, lastArg, index) => {
// use deep equal for first arg
if(index === 0) {
return deepEqual(newArg, lastArg);
}
// use shallow equal for all other arguments
return newArg === lastArg;
}
const fn = (...args) => {
console.log('called with', ...args);
};
const memoized = memoizeOne(fn, myEqualFn);
memoized({hello: 'world'}, 5);
// console.log('called with', {hello: 'world'}, 5);
memoized({hello: 'world'}, 5);
// no call to console.log
# yarn
yarn add memoize-one
# npm
npm install memoize-one --save
import memoizeOne from 'memoize-one';
If you are in a CommonJS environment (eg Node), then you will need to add .default
to your import:
const memoizeOne = require('memoize-one').default;
this
memoize-one
correctly respects this
controlThis library takes special care to maintain, and allow control over the the this
context for both the original function being memoized as well as the returned memoized function. Both the original function and the memoized function's this
context respect all the this
controlling techniques:
new
)call
, apply
, bind
);obj.foo()
);window
or undefined
in strict mode
);this
)null
as this
to explicit binding)this
is considered an argument changeChanges to the running context (this
) of a function can result in the function returning a different value even though its arguments have stayed the same:
function getA() {
return this.a;
}
const temp1 = {
a: 20,
};
const temp2 = {
a: 30,
}
getA.call(temp1); // 20
getA.call(temp2); // 30
Therefore, in order to prevent against unexpected results, memoize-one
takes into account the current execution context (this
) of the memoized function. If this
is different to the previous invocation then it is considered a change in argument. further discussion.
Generally this will be of no impact if you are not explicity controlling the this
context of functions you want to memoize with explicit binding or implicit binding. memoize-One
will detect when you are manipulating this
and will then consider the this
context as an argument. If this
changes, it will re-execute the original function even if the arguments have not changed.
throw
sThere is no caching when your result function throws
If your result function throw
s then the memoized function will also throw. The throw will not break the memoized functions existing argument cache. It means the memoized function will pretend like it was never called with arguments that made it throw
.
const canThrow = (name: string) => {
console.log('called');
if(name === 'throw') {
throw new Error(name);
}
return { name };
}
const memoized = memoizeOne(canThrow);
const value1 = memoized('Alex');
// console.log => 'called'
const value2 = memoized('Alex');
// result function not called
console.log(value1 === value2);
// console.log => true
try {
memoized('throw');
// console.log => 'called'
} catch(e) {
firstError = e;
}
try {
memoized('throw');
// console.log => 'called'
// the result function was called again even though it was called twice
// with the 'throw' string
} catch(e) {
secondError = e;
}
console.log(firstError !== secondError);
const value3 = memoized('Alex');
// result function not called as the original memoization cache has not been busted
console.log(value1 === value3);
// console.log => true
memoize-one
is super lightweight at minified and gzipped. (1KB
= 1,024 Bytes
)
memoize-one
performs better or on par with than other popular memoization libraries for the purpose of remembering the latest invocation.
Results
The comparisions are not exhaustive and are primiarly to show that memoize-one
accomplishes remembering the latest invocation really fast. The benchmarks do not take into account the differences in feature sets, library sizes, parse time, and so on.
Flow
types for safer internal execution and external consumption. Also allows for editor autocompletion.FAQs
A memoization library which only remembers the latest invocation
The npm package memoize-one receives a total of 9,668,628 weekly downloads. As such, memoize-one popularity was classified as popular.
We found that memoize-one demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
Security News
NVD’s backlog surpasses 20,000 CVEs as analysis slows and NIST announces new system updates to address ongoing delays.
Security News
Research
A malicious npm package disguised as a WhatsApp client is exploiting authentication flows with a remote kill switch to exfiltrate data and destroy files.